package com.example.test01.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.test01.mapper.TestMapper;
import com.example.test01.pojo.User;
import com.example.test01.service.testService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "用户接口")
@RestController
public class testController {


    @Autowired
    private testService testService;
    @Autowired
    private TestMapper  testMapper;

    //测试
    @Operation(summary = "测试接口", description = "测试接口")
    @GetMapping("/")
    public String home() {
        return "Hello, Spring Boot!";
    }

    //查询所有用户
    @Operation(summary = "查询所有用户", description = "返回所有用户列表")
    @GetMapping("/find")
    public List<User> find() {
        return testService.list();
    }

    //新增用户
    @PutMapping("/add")
    @Operation(summary = "新增用户", description = "用户id自增无需填入，自动填充插入时间")
    public String add(@RequestBody  User user) {
        System.out.println(user);
        if(user == null) {
            return "user is null";
        }
        // 假设你有 UserMapper 或 Repository
        testMapper.insert(user);
        return "success";

    }

    //更新用户
    @PutMapping("/update/{id}")
    @Operation(summary = "根据ID部分更新用户", description = "仅更新传入的非空字段；自动更新时间")
    public String update(@Parameter(description = "用户ID", required = true)
                         @PathVariable Integer id,
                         @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "要更新的字段（name/age 可选）", required = true)
                         @Valid @RequestBody User updatedUser) {

        // 根据路径参数中的 ID 查询用户
        User user = testService.getById(id);
        if (user == null) {
            return "user is null"; // 用户不存在
        }

        // 更新用户信息（仅更新非空字段）
        if (updatedUser.getName() != null) {
            user.setName(updatedUser.getName());
        }
        if (updatedUser.getAge() != null) {
            user.setAge(updatedUser.getAge());
        }

        // 调用服务层更新用户
        user.setUpdateTime(null); // 关键：让MP自动填充更新时间
        boolean result = testService.updateById(user);

        // 返回结果
        return result ? "success" : "update failed";

    }



    //删除用户
    @Operation(summary = "根据ID删除用户", description = "根据ID删除用户")
    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        User user = testService.getById(id);
        if (user == null) {
            return "user is null"; // 用户不存在
        }
        testMapper.deleteById(user.getId());
        return "success";
    }



}
